package com.example.myapplication4;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.data.DatabaseHelper;
import ohos.data.dataability.DataAbilityUtils;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import ohos.utils.PacMap;

import java.io.FileDescriptor;

//DataAbility  负责处理数据库的相关操作
public class UUDataAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private RdbStore rdbStore;
    private StoreConfig config=StoreConfig.newDefaultConfig("UserStore.db");
    private RdbOpenCallback callback=new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore rdbStore) {
            //分别创建关于用户信息，避险调查，房屋破坏的数据表
            rdbStore.executeSql("create table if not exists users(userId integer primary key autoincrement,userName not null,userPassword not null unique)");
            rdbStore.executeSql("create table if not exists history(userId integer primary key autoincrement,diCat not null,diNam not null,diListen not null,diEscape not null,diTime not null)");
            rdbStore.executeSql("create table if not exists destroy(userId integer primary key autoincrement,diCat not null,diNam not null,diTroychengdu not null,diTime not null)");
        }

        @Override
        public void onUpgrade(RdbStore rdbStore, int i, int i1) {

        }
    };
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        HiLog.info(LABEL_LOG, "UserStore.db");

        DatabaseHelper helper=new DatabaseHelper(this);

        //初始化与数据库的连接
        rdbStore=helper.getRdbStore(config,1,callback);

    }

    @Override
    public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates) {
        RdbPredicates rdbPredicates= DataAbilityUtils.createRdbPredicates(predicates,uri.getLastPath());
        ResultSet resultSet=rdbStore.query(rdbPredicates,columns);
        return resultSet;
    }


    @Override
    public int insert(Uri uri, ValuesBucket value) {
        int i=-1;
        String path=uri.getLastPath();
        //判断要访问的是哪一个数据表
        if("users".equalsIgnoreCase(path)){
            i=(int)rdbStore.insert("users",value);
        }else if("history".equalsIgnoreCase(path)){
            i=(int)rdbStore.insert("history",value);
        }else if("destroy".equalsIgnoreCase(path)){
            i=(int)rdbStore.insert("destroy",value);
        }
        return i;
    }

    @Override
    public int delete(Uri uri, DataAbilityPredicates predicates) {
        return 0;
    }

    @Override
    public int update(Uri uri, ValuesBucket value, DataAbilityPredicates predicates) {
        return 0;
    }


}